<?php

include_once AF_BASE_DIR . 'AFException.class.php';

class AFDebugException extends AFException {};

class AFFunctions
{
	const AFModule = 'module';
	const AFInterface = 'interface';

	public static function walk($dirs, $callback, $includePath = FALSE)
	{
		if(!is_array($dirs))
		{
			$dirs = array($dirs);
		}
		foreach($dirs as $dir)
		{
			if(!is_dir($dir))
			{
				continue;
			}
			$dh = opendir($dir);
			while($item = readdir($dh))
			{
				if($item[0] != '.')
				{
					$callback(($includePath ? (rtrim($dir, AF_SEP) . AF_SEP) : '') . $item);
				}
			}
		}
	}
	public static function highlightLine($str)
	{
		$hl = highlight_string('<'.'?php '.$str.' ?'.'>', TRUE);
		$hl = str_replace(array('&lt;?php&nbsp;', '?&gt;', "\n"), array('', '', ''), $hl);
		return $hl;
	}

	public static function slug($value)
	{
		return preg_replace(array('/^[0-9]/', '/[^a-z0-9_]/'), array('_', '_'), strtolower($value));
	}

//	public static function import($file)
//	{
//		echo get_include_path();
//		include_once $file;
//	}

	public static function stop($message = 'unknown')
	{
		throw new AFDebugException('Cause of death: "'.$message.'"', 1);
	}

	public static function _v($value, $default = NULL)
	{
		return $value ? $value : $default;
	}

	public static function _va($array, $key, $value = NULL)
	{
		return isset($array[$key]) ? $array[$key] : $value;
	}

	public static function hash($src = NULL, $fn = 'md5')
	{
		return $src ? $fn($src) : md5(microtime(TRUE) . rand(0, 10000));
	}

	public static function highlightXML($s)
	{       
		$s = htmlspecialchars($s);
		$s = preg_replace("#&lt;([/]*?)(.*)([\s]*?)&gt;#sU",
			"<font color=\"#0000FF\">&lt;\\1\\2\\3&gt;</font>",$s);
		$s = preg_replace("#&lt;([\?])(.*)([\?])&gt;#sU",
			"<font color=\"#800000\">&lt;\\1\\2\\3&gt;</font>",$s);
		// Tags
		$s = preg_replace("#&lt;([^\s\?/=\$])(.*)([\[\s/]|&gt;)#iU",
			"&lt;<font color=\"#808000\"><b>\\1\\2</b></font>\\3",$s);

		// AFW tags
		$s = preg_replace('/&lt;\$(.*)\$&gt;/sU', '<b style="color:#007700"><u>&lt;\$\1\$&gt;</u></b>', $s);

		// Tag closes
		$s = preg_replace("#&lt;([/])([^\s]*?)([\s\]]*?)&gt;#iU",
			"&lt;\\1<font color=\"#808000\"><b>\\2</b></font>\\3&gt;",$s);
		// Params
		$s = preg_replace("#([^\s]*?)\=(&quot;|')(.*)(&quot;|')#isU",
			"<font color=\"#800080\"><b>\\1</b></font>=<font color=\"#FF00FF\">\\2\\3\\4</font>",$s);
		$s = preg_replace("#&lt;(.*)(\[)(.*)(\])&gt;#isU",
			"&lt;\\1<font color=\"#800080\">\\2\\3\\4</font>&gt;",$s);
		return $s;
	}

	public static function trailingSlash($s, $add = TRUE)
	{
		return rtrim($s, '/') . ($add ? '/' : '');
	}

	public static function getExt($path)
	{
		preg_match_all('/\.([a-zA-Z0-9_-]+)$/', $path, $match, PREG_SET_ORDER);
		return count($match) ? $match[0][1] : NULL;
	}

	public static function checkExt($path, $ext)
	{
		return strpos($path, $ext) == (strlen($path) - strlen($ext));
	}
}

class FN extends AFFunctions {};

?>
